﻿//----------------------------------------------------

#region 命名空间

//    版权：
//    作者：
//建立时间：2012-09-11 00:00:33
//    描述：
//----------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WinnerCMS.Common;
using WinnerCMS.Data;
using WinnerCMS.Model;
using WinnerCMS.Model.Enum;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 业务逻辑类 WinnerCMS_Model 的摘要说明。
    /// </summary>
    /// <remarks>请注意对模型的修改删除都必须进行清除WinnerCMS_Model_Info开头的缓存</remarks>
    public class ModelManage
    {
        private static readonly ModelDal Dal;
        private static readonly Dictionary<byte, Model.Model> DicInfos;

        static ModelManage()
        {
            Dal = new ModelDal();
            DicInfos = new Dictionary<byte, Model.Model>();
            DicInfos = Dal.GetList();
        }

        #region 添加模型

        /// <summary>
        /// 添加模型
        /// </summary>
        /// <param name="model"></param>
        /// <param name="dlFilter"></param>
        /// <returns></returns>
        [Logging("添加模型"), ExceptionCall]
        public Result Add(Model.Model model, DataList dlFilter)
        {
            Result res = new Result();
            StringBuilder winner = new StringBuilder();
            if (model.BaseModel != "Shop" || model.BaseModel != "Ask")
            {
                foreach (DataListItem dli in dlFilter.Items)
                {
                    foreach (Control c in dli.Controls)
                    {
                        if (c is CheckBox)
                        {
                            CheckBox cb = c as CheckBox;
                            winner.AppendFormat("{0}|{1}|{2};", cb.Text, cb.ToolTip, cb.Checked);
                        }
                    }
                }
                model.Filter = winner.ToString();

                if (model.Filter.Length == 0)
                {
                    res.Errors = "字段不能为空";
                    return res;
                }
            }
            model.Hide = false;
            if (model.Id == 0)
            {
                #region 验证

                if (model.DataTable.StartsWith("WinnerCMS_Extend_", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    res.Errors = "扩展的模型表名必须用“WinnerCMS_Extend_”作前缀，以避免冲突。";
                    return res;
                }
                if (model.DataTable.Equals("WinnerCMS_Extend_", StringComparison.CurrentCultureIgnoreCase))
                {
                    res.Errors = "扩展的模型表名必须要填写。";
                    return res;
                }

                #endregion

                model.Id = Dal.Add(model);

                if (model.BaseModel == ModelType.Article.ToString())
                {
                    new RightsManage().Add("2");
                    new MemuDal().Add(2);
                }
                else if (model.BaseModel == ModelType.Soft.ToString())
                {
                    new RightsManage().Add("1");
                    new MemuDal().Add(1);
                }
                else if (model.BaseModel == ModelType.Photo.ToString())
                {
                    new RightsManage().Add("3");
                    new MemuDal().Add(3);
                }

                #region 复制文件

                string Path1 = HttpContext.Current.Server.MapPath("~/" + model.BaseModel);
                string Path2 = HttpContext.Current.Server.MapPath(model.HtmlSavePath);
                try
                {
                    if (Directory.Exists(Path2) == false)
                    {
                        Directory.CreateDirectory(Path2);
                    }

                    DirectoryInfo di = new DirectoryInfo(Path1);
                    foreach (FileInfo fi in di.GetFiles())
                    {
                        if (fi.Extension.ToLower() == ".aspx")
                        {
                            string NewFileFullName = Path2 + fi.Name;

                            FileInfo NewFile = new FileInfo(NewFileFullName);
                            //如果原来的位置已经有文件而且是只读的就去掉只读属性
                            if (NewFile.Exists && NewFile.Attributes == FileAttributes.ReadOnly)
                            {
                                NewFile.Attributes = FileAttributes.Normal;
                            }

                            fi.CopyTo(NewFileFullName, true);
                        }
                    }
                }
                catch
                {
                    res.Errors = "建立新模型成功！但是复制原基础模型的文件到新位置，发生一般性错误，请自己复制。";
                }

                #endregion
            }
            else
            {
                Dal.Edit(model);
            }

            ClearCache();
            new MenuManage().ClearCache();
            return res;
        }

        #endregion

        #region 删除模型

        /// <summary>
        /// 删除模型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Logging("删除模型"), ExceptionCall]
        public Result Delete(byte id)
        {
            Result res = new Result();

            var model = GetInfo(id);

            if (model == null)
            {
                res.Errors = "数据已经不存在！";
                return res;
            }

            Dal.Delete(id);

            new RightsManage().Delete(id.ToString());
            new MemuDal().Delete(id);
            new CategoryManage().Delete(id);
            ClearCache();

            new MenuManage().ClearCache();

            return res;
        }

        #endregion

        #region 加载数据

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public static Model.Model GetInfo(byte modelId)
        {
            return DicInfos[modelId];
        }

        #endregion

        #region 清除本类建立的缓存

        /// <summary>
        /// 清除本类建立的缓存
        /// </summary>
        public void ClearCache()
        {
            CacheStorager.CMSCaches.Context.FlushAll();
        }

        #endregion

        #region 取得模型名称

        /// <summary>
        /// 取得模型名称
        /// </summary>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public static string GetModelName(byte modelId)
        {
            var model = GetInfo(modelId);
            return model.ModelName;
        }

        #endregion

        #region 取得模型的数据库表

        /// <summary>
        /// 取得模型的数据库表
        /// </summary>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public static string GetTableName(byte modelId)
        {
            var model = GetInfo(modelId);
            return model.DataTable;
        }

        #endregion

        #region 基本模型

        /// <summary>
        /// 基本模型
        /// </summary>
        public static ModelType GetBaseModel(byte modelId)
        {
            var model = GetInfo(modelId);
            switch (model.BaseModel)
            {
                case "Article":
                    return ModelType.Article;
                case "Soft":
                    return ModelType.Soft;
                case "Photo":
                    return ModelType.Photo;
                case "Shop":
                    return ModelType.Shop;
                case "Ask":
                    return ModelType.Ask;
                default:
                    throw new NotSupportedException("非法模型标识");
            }
        }

        #endregion

        #region 内容名称

        /// <summary>
        /// 内容名称
        /// </summary>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public static string GetContentName(byte modelId)
        {
            var model = GetInfo(modelId);
            return model.ContentName;
        }

        #endregion

        #region 内容单位

        /// <summary>
        /// 内容单位
        /// </summary>
        public static string GetContentUnit(byte modelId)
        {
            var model = GetInfo(modelId);
            return model.ContentUnit;
        }

        #endregion

        #region 默认自动审核

        /// <summary>
        /// 内容单位
        /// </summary>
        public static byte GetPass(byte modelId)
        {
            var model = GetInfo(modelId);
            return Convert.ToByte(model.AdminPass);
        }

        #endregion

        #region 模型保存的文件夹

        /// <summary>
        /// 模型保存的文件夹
        /// </summary>
        public static string GetHtmlSavePath(byte modelId)
        {
            var model = GetInfo(modelId);
            return model.HtmlSavePath;
        }

        #endregion

        #region 前台分页行数

        /// <summary>
        /// 前台分页行数
        /// </summary>
        public static int GetPageSize(byte modelId)
        {
            var model = GetInfo(modelId);
            return Convert.ToInt32(model.PageSize);
        }

        #endregion

        #region 绑定字段选择列表

        /// <summary>
        /// 绑定字段选择列表
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="DL_Filter"></param>
        public void Filter(string filter, DataList DL_Filter)
        {
            using (DataTable dt = new DataTable())
            {
                DataRow dr;

                dt.Columns.Add(new DataColumn("Explain", Type.GetType("System.String")));
                dt.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
                dt.Columns.Add(new DataColumn("Checked", Type.GetType("System.Boolean")));

                foreach (string str in filter.Split(';'))
                {
                    if (str.Length == 0)
                    {
                        continue;
                    }
                    string[] strRow = str.Split('|');
                    dr = dt.NewRow();
                    dr["Explain"] = strRow[0];
                    dr["Name"] = strRow[1];
                    dr["Checked"] = bool.Parse(strRow[2]);

                    dt.Rows.Add(dr);
                }

                DL_Filter.DataSource = dt;
                DL_Filter.DataBind();
            }
        }

        #endregion

        #region 绑定DDL控件的数据源

        /// <summary>
        /// 绑定DDL控件的数据源
        /// </summary>
        /// <param name="DDL"></param>
        /// <param name="strNewListItem"></param>
        public void BindDDL(ListControl DDL, string strNewListItem)
        {
            DDL.DataSource = Dal.GetList().Values;
            DDL.DataTextField = "ModelName";
            DDL.DataValueField = "ID";
            DDL.DataBind();

            if (strNewListItem.Length > 0)
            {
                DDL.Items.Insert(0, new ListItem(strNewListItem, "0"));
            }
        }

        #endregion

        #region 取得所有字段

        /// <summary>
        /// 取得所有字段
        /// </summary>
        /// <param name="name"></param>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public void GetFields(ListBox name, byte modelId)
        {
            name.DataSource = Dal.GetFields(modelId);

            name.DataTextField = "COLUMN_NAME";
            name.DataValueField = "COLUMN_NAME";
            name.DataBind();
        }

        #endregion

        #region 系统的模型统计

        /// <summary>
        /// 系统的模型统计
        /// </summary>
        /// <returns></returns>
        public void ModelsInTheCMS(Repeater pep)
        {
            pep.DataSource = Dal.ModelsInTheCMS();
            pep.DataBind();
        }

        #endregion

        #region 取得数据

        /// <summary>
        /// 取得数据
        /// </summary>
        /// <returns></returns>
        public IList<Model.Model> GetList()
        {
            return DicInfos.Values.ToList();
        }

        #endregion

        #region 数据库表数据量统计

        /// <summary>
        /// 数据库表数据量统计
        /// </summary>
        /// <param name="tableName">数据库表</param>
        /// <returns></returns>
        public int GetDBTableCount(string tableName)
        {
            return Dal.GetDBTableCount(tableName);
        }

        #endregion

        #region 数据库数据量统计

        /// <summary>
        /// 数据库数据量统计
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, int> GetDBCount()
        {
            return Dal.GetDBCount();
        }

        #endregion
    }
}